<template>
    <div class="content_panel project_modules">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{$t('finance.repayRecord')}}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row>
                    <el-col :span="4">
                        <el-form-item prop="orderId" label="">
                            <el-input v-model="form.orderId" :placeholder="$t('common.innerOrderId')" clearable></el-input><!--内部订单号-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="userPhone" label="">
                            <el-input v-model="form.userPhone" :placeholder="$t('common.mobileNumber')" clearable></el-input><!--手机号码-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="userId" label="">
                            <el-input v-model="form.userId" placeholder="User ID" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="appName" label="">
                            <select-app-list v-model="form.appName" :placeholder="$t('system.appName')"></select-app-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" v-if="showCollectionUser">
                        <el-form-item prop="collectionUserName">
                            <select-account-list :type="selectDataType" v-model="form.collectionUserName" :placeholder="$t('common.recruiter')"></select-account-list>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" v-if="showCollectionType">
                        <el-form-item prop="teamName">
                            <el-select v-model="form.teamName" clearable :placeholder="$t('collection.colPhase')" style="width: 100%"><!--催收阶段-->
                                <el-option v-for="item in phaseData" :key="item.id" :value="item.name" :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- 伪名 -->
                    <el-col :span="4">
                        <el-form-item prop="kana"> <!--姓名-->
                            <select-kana-list v-model="form.kana" :multiple="false" :placeholder="$t('finance.pseudonym')"></select-kana-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                    <!--放款类型-->
                    <el-col :span="4">
                        <el-form-item prop="repayType" label="">
                            <el-select v-model="form.repayType" :placeholder="$t('common.repaymentType')" clearable style="width: 100%">
                                <el-option v-for="item in keyMap.repaymentType" :key="item.value" :value="item.value" :label="item.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item prop="actRepayTime" style="width: 100%"><!--实际还款时间-->
                            <el-date-picker
                                :picker-options="pickerOptions"
                                v-model="form.actRepayTime"
                                type="datetimerange"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="timestamp"
                                :editable="false"
                                style="width: 100%;"
                                range-separator="-"
                                :default-time="['00:00:00', '23:59:59']"
                                :start-placeholder="$t('common.actRepayStartTime')"
                                :end-placeholder="$t('common.actRepayEndTime')"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-button @click="search" type="primary">{{ $t('common.search') }}</el-button>
                        <el-button @click="exportData" type="primary">{{ $t('common.export') }}</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div><!--content_panel_top-->

        <div class="module_content">
            <div class="content_panel project_modules">
                <div class="table_list">
                    <div class="totalAmount"><span>{{ $t('common.totalRepayment') }}：PHP {{ totalRepayAmount }}</span></div>
                    <el-table ref="table" :data="tableData" style="width: 100%;" :max-height="tableMaxHeight" :highlight-current-row="true">
                        <el-table-column prop="orderId" :label="$t('common.innerOrderId')" min-width="180"></el-table-column><!--内部订单号-->
                        <el-table-column prop="userId" label="User ID" min-width="120"></el-table-column>
                        <el-table-column prop="userName" :label="$t('common.name')" min-width="160"></el-table-column><!--姓名-->
                        <!--手机号-->
                        <!-- <el-table-column prop="userPhone" :label="$t('common.mobileNumber')" min-width="120"></el-table-column> -->
                        <el-table-column :label="$t('common.repayAmount')" prop="repayAmount" width="100"><!--还款金额-->
                            <template slot-scope="{ row }">{{ row.repayAmount | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('finance.repaymentPrincipal')" prop="repayPrincipal" width="100"><!--还款本金-->
                            <template slot-scope="{ row }">{{ row.repayPrincipal | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('finance.repaymentPenaltyInterest')" prop="interestPenalties" width="100"><!--还款罚息-->
                            <template slot-scope="{ row }">{{ row.interestPenalties | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column align="left" :label="$t('common.actRepayTime')" min-width="170" prop="repayCompletionTime"><!--实际还款时间-->
                            <template slot-scope="{ row }">{{ row.repayCompletionTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                        </el-table-column>
                        <el-table-column prop="teamName" :label="$t('collection.colPhase')" min-width="120"></el-table-column><!--催收阶段-->
                        <el-table-column prop="collectionUserName" :label="$t('common.recruiter')" min-width="120"></el-table-column><!--催收员-->
                        <el-table-column :label="$t('system.appName')" prop="appName" min-width="130">
                            <template slot-scope="{ row }">{{ row.appName | switchAppName }}</template>
                        </el-table-column><!--APP名称-->
                        <el-table-column :label="$t('finance.pseudonym')" prop="kana" min-width="130">
                            <template slot-scope="{ row }">{{ row.kana | switchProductName }}</template>
                        </el-table-column><!--伪名-->

                        <el-table-column :label="$t('common.repaymentType')" prop="appType" min-width="180"><!--放款类型-->
                            <template slot-scope="{ row }">{{ row.repayType | SwitchRepaymentType }}</template>
                        </el-table-column>
                    </el-table>
                    <!--分页组件-->
                    <pagination @pageChange="pageChange" :page="page"><!--分页组件--></pagination>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import Pagination from '@/components/pagination';
    import mixin from '@/service/mixin';
    import SelectAppList from '@/components/select-app-list';
    import SelectAccountList from '@/components/select-account-list';
    import storage from '@/libs/storage';
    import {keyMap} from '@/config';
    import SelectKanaList from '@/components/select-kana-list';

    let that = null;
    export default {
        name: 'collection-orderManage-repayRecord',
        components: {
            Pagination,
            SelectAppList,
            SelectAccountList,
            SelectKanaList
        },
        mixins: [mixin],
        data() {
            return {
                keyMap,
                tableData: [],
                totalRepayAmount:0,
                showCollectionUser:false,//展示催收员
                showCollectionType:false,//展示催收阶段
                form: {
                    orderId: '',
                    userPhone: '',
                    userId: '',
                    appName: '',
                    repayType:'',
                    kana:'',
                    collectionUserName: '',
                    teamName: '',
                    actRepayTime: []
                },
                phaseData: [],
                rules: {
                    orderId: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                    userPhone: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                    userId: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                },
                selectDataType: {
                    systemType: 'recruiter',
                    roleCode: 127
                },
                roleCode: [],
                selectDate: ''
            };
        },
        computed: {
            hasPermission () {
                const list = ['127', '128', '140', '141']
                if (this.roleCode.length > 0 ) {
                    const bol = this.roleCode.every(item => list.findIndex(item1 => item1 === item) > -1)
                    return bol
                }
                return false
            },
            pickerOptions () {
                const data = {
                    onPick: ({ maxDate, minDate }) => {
                        console.log(maxDate, minDate)
                        this.selectDate = ''
                        let now = new Date()
                        now.setHours(23, 59, 59, 999)
                        // 催收员或催收组长
                        console.log(this.hasPermission)
                        if (this.hasPermission) {
                            this.selectDate = now
                            console.log(1111111)
                        }
                    },
                    disabledDate: time => {
                        if (this.selectDate) {
                            const date = this.selectDate
                            const minTime = new Date(date.setDate(date.getDate() - 20)).getTime()
                            const maxTime = new Date(date.setDate(date.getDate() + 20)).getTime()
                            return time.getTime() < minTime || time.getTime() > maxTime
                        } else {
                            return false
                        }
                    }
                }
                return data
            }
        },
        methods: {
            getUserRoleCode(collectionUserName) {
                const params = {
                    isPage: 1,
                    page: {
                        pageNo: 1,
                        pageSize: 10000
                    },
                    roleCode: '', // 角色类型
                    collectionUserName: collectionUserName, // 账号类型
                    active:'', // 账号状态
                };
                this.tableData = [];
                this.$api.collection.queryCollectorRole().then((res) => {
                    console.log(res)
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.roleCode = data || []
                        if(data&&data.length>0){
                            let roleCode = data[0];
                            if (roleCode == '129') { //主管
                                this.selectDataType.roleCode = '127,141';
                                this.showCollectionUser = true//展示催收员
                                this.showCollectionType = true//展示催收阶段
                            }else if(roleCode == '128') { // 催收组长
                                this.selectDataType.roleCode = 127;
                                this.showCollectionUser = true//展示催收员
                                this.showCollectionType = false//展示催收阶段
                            }else if(roleCode == '140') { //预催收组长
                                this.selectDataType.roleCode = 141;
                                this.showCollectionUser = true//展示催收员
                                this.showCollectionType = false//展示催收阶段
                            }else{//组员
                                this.showCollectionUser = false//展示催收员
                                this.showCollectionType = false//展示催收阶段
                            }
                        }else{
                            console.warn('未查到用户角色信息')
                        }
                        this.getTableData();
                        // if (data.resultData && data.resultData.length === 0 && data.page.totalRecord > 0 && this.page.currentPage > 1) {
                            // this.page.currentPage--;
                            // this.getTableData();
                            // return;
                        // }
                        // this.tableData = data.resultData;
                        // this.tableData.forEach((item) => {
                            // item.isCollect = +item.isCollect === 1;
                        // });
                        // this.listRoleType = this.searchForm.roleType;
                        // this.setPage(data.page, this.page);
                        // this.tableMaxHeight = window.document.body.clientHeight - 180;
                    }
                });
            },
            // 获取列表数据
            getTableData(page = this.page) {
                const form = this.form;
                const params = this.fillParams(page);
                this.$api.collection.listclrepayrecord(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.tableData = data.resultData;
                        this.setPage(data.page, this.page);
                        this.totalRepayAmount = data.totalRepayAmount
                    }
                    this.tableMaxHeight = document.body.clientHeight - 270;
                });
            },
            search() {
                this.$refs.form.validate(val => {
                    if (val) {
                        this.page.currentPage = 1;
                        this.getTableData();
                    }
                });
            },
            // 导出列表数据
            exportData() {
                this.$refs.form.validate(val => {
                    if (val) {
                        const params = this.fillParams();
                        const user = this.$storage.get('user');
                        const language = this.$storage.getLocal('language');
                        params.language = language;
                        params.token = user.token;
                        const {$apiConf} = this;
                        const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.collection.exprotclrepayrecord, ['page']);
                        this.$openNewBlank(url);
                    }
                });
            },
            // 配置查询和导出参数
            fillParams(page = this.page) {
                const form = this.form;
                const params = {
                    orderId: this.form.orderId,
                    userPhone: this.form.userPhone,
                    userId: this.form.userId,
                    appName: this.form.appName,
                    repayType:this.form.repayType,
                    kana:this.form.kana,
                    collectionUserName: this.form.collectionUserName,
                    teamName: this.form.teamName,
                    startTime: '',
                    endTime: '',
                    page: {
                        pageNo: page.currentPage,
                        pageSize: this.page.pageSize
                    }
                };
//                Object.keys(form).forEach(key => {
//                    if (typeof form[key] === 'string' && form[key]) {
//                        form[key] = form[key].trim();
//                        params[key] = form[key];
//                    }
//                });
                if (form.actRepayTime && form.actRepayTime.length >= 2) {
                    params.startTime = form.actRepayTime[0];
                    params.endTime = form.actRepayTime[1];
                } else {
                    if (this.hasPermission) {
                        let date = new Date()
                        date.setHours(23, 59, 59, 999)
                        params.startTime = new Date(date.setDate(date.getDate() - 20)).getTime()
                        params.endTime = new Date(date.setDate(date.getDate() + 20)).getTime()
                    }
                }
                return params;
            },
            // 获取阶段名称筛选数据
            getPhaseData() {
                const params = {
                    name: '',
                    active: 0
                };
                this.$api.collection.getCollectStages(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.phaseData = data;
                    }
                });
            }
        },
        filters: {
            switchStatus(status) {
                switch (status + '') {
                    case '0':
                        return that.$t('collection.activated');// 已启用
                    case '1':
                        return that.$t('collection.closed');// 已关闭
                    default:
                        return status;
                }
            }
        },
        created() {
            that = this;
            let {username} = storage.get('user');
            this.getUserRoleCode(username)
            this.getPhaseData();
        }
    }
</script>
<style lang="scss" scoped>
    [data-page=collection-orderManage-repayRecord] {
        .el-col {
            padding-left: 10px;
        }
        .el-table .cell, .el-table th > .cell {
            word-break: keep-all;
            word-wrap: break-word;
        }
    }
</style>

